<template>
  <el-drawer v-model="state.open" destroy-on-close title="公告" @close="close" @open="open">
    <template #default>
      <el-tabs style="margin-bottom: 15px;" type="border-card">
        <el-form ref="editForm" :model="data" :rules="rules" label-width="auto">
          <el-tab-pane label="公告信息">
            <el-form-item label="标题" prop="title">
              <el-input v-model.trim="data.title" clearable/>
            </el-form-item>
            <el-form-item label="内容" prop="content">
              <Editor v-model="data.content" :init="{
                resize: false, // 不允许用户调整大小
                language: 'zh-Hans', // 汉化
                branding: false, // 隐藏tinymce右下角水印
                convert_urls: false, // 不自动转换链接地址
                plugins: 'autoresize fullscreen image lists table', // 插件
                menubar: false, // 菜单栏
                statusbar: false, // 状态栏
                max_height: 500,
                autoresize_bottom_margin: 10,
                toolbar: 'image alignleft aligncenter alignright alignjustify lineheight | numlist bullist table | fontsize | forecolor backcolor | bold italic underline strikethrough | superscript subscript | hr | ', // 工具栏
                images_reuse_filename: true,
                font_size_formats: '12px 14px 16px 18px 24px 36px',
                images_upload_handler: this.imageUploadHandler,
                content_style:'p{margin: 0;}body{font-size:14px}',
              }" style="width: 100%;"/>
            </el-form-item>
          </el-tab-pane>
        </el-form>
      </el-tabs>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="close">取消</el-button>
        <el-popconfirm v-if="state.id" cancel-button-text="否" confirm-button-text="是" title="确定删除该公告?" width="250" @confirm="del">
          <template #reference>
            <el-button type='danger'>删除</el-button>
          </template>
        </el-popconfirm>
        <el-button v-if="state.id" type="warning" @click="upsert">更新</el-button>
        <el-button v-else type="primary" @click="upsert">保存</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script>
import Editor from '@tinymce/tinymce-vue'

export default {
  name: "Create",
  props: ['state'],
  components: {Editor},
  data() {
    return {
      data: {},
      rules: {
        title: [
          {
            required: true, trigger: ['change', 'blur'], validator: (_, value, callback) => {
              if (!value) return callback(new Error('请输入公告标题'))
              callback()
            }
          }
        ],
        content: [
          {
            required: false, trigger: ['change', 'blur'], validator: (_, value, callback) => {
              if (!value ) return callback(new Error('请输入公告内容'))
              callback()
            }
          }
        ]
      }
    }
  },
  methods: {
    imageUploadHandler: (blobInfo, progress) => new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();
      xhr.withCredentials = false;
      xhr.open('POST', import.meta.env.VITE_API_PREFIX + '/image/upload');
      xhr.setRequestHeader('X-Token', localStorage.getItem('X-Token'))

      xhr.upload.onprogress = (e) => {
        progress(e.loaded / e.total * 100);
      };

      xhr.onload = () => {
        if (xhr.status === 200) return resolve(JSON.parse(xhr.responseText).data);
        if (xhr.status === 401) return this.$router.push('/login')
        reject('图片上传失败: ' + xhr.status);
      };

      xhr.onerror = () => {
        reject('图片上传失败: ' + xhr.status);
      };

      const formData = new FormData();
      formData.append('file', blobInfo.blob(), blobInfo.filename());
      xhr.send(formData);
    }),
    async open() {
      if (this.state.id) {
        this.data = await this.post('/notice/get', {id: this.state.id})
      }
    },
    async upsert() {
      await this.$refs['editForm'].validate(async (valid, fields) => {
        if (!valid) return
        await this.post('/notice/upsert', {
          id: this.state.id,
          title: this.data.title,
          content: this.data.content,
        });
        this.$emit('updated')
        this.close()
      })
    },
    async del() {
      await this.post('/notice/delete', {
        id: this.state.id,
      });
      this.$emit('updated')
      this.close()
    },
    close() {
      this.state.open = false
      this.$refs['editForm'].resetFields()
    },
  }
}
</script>

<style scoped>
:deep(.cm-scroller) {
  min-height: calc(100vh - 520px);
}
</style>